import jwt
from datetime import datetime, timedelta, timezone
from flask import current_app

def generate_jwt_token(user_id):
    """
    生成JWT令牌。
    :param user_id: 用户ID
    :return: JWT令牌
    """

    expiration = datetime.now(timezone.utc) + timedelta(hours=24)

    payload = {
        'user_id': user_id,
        'exp': expiration
    }

    token = jwt.encode(
        payload,
        current_app.config['JWT_SECRET_KEY'],
        algorithm='HS256'
    )
    return token

def verify_jwt_token(token):
    """
    验证JWT令牌。
    :param token: JWT令牌
    :return: user_id
    """

    try:
        payload = jwt.decode(
            token,
            current_app.config['JWT_SECRET_KEY'],
            algorithms=['HS256']
        )
        return payload['user_id']
    
    except jwt.exceptions.ExpiredSignatureError:#超时
        return None
    
    except jwt.exceptions.DecodeError:#无效令牌
        return None

